package edu.caltech.cs.cs141.CopilotWeb.server;


import java.io.DataInputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


import edu.caltech.cs.cs141.CopilotWeb.server.PMF;
import edu.caltech.cs.cs141.CopilotWeb.shared.AbPoint;
import edu.caltech.cs.cs141.CopilotWeb.shared.Coordinate;

public class parseUpload extends HttpServlet{

	private static final Logger log =
	      Logger.getLogger(parseUpload.class.getName());

	  public void doPost(HttpServletRequest req, HttpServletResponse res)
	      throws ServletException, IOException {
		  
		ObjectifyService.register(TripData.class);
		Objectify ofy = ObjectifyService.begin();

	    try {
	      ServletFileUpload upload = new ServletFileUpload();
	      FileItemIterator iterator = upload.getItemIterator(req);
	      while (iterator.hasNext()) {
	        FileItemStream item = iterator.next();
	        InputStream stream = item.openStream();
	        DataInputStream data = new DataInputStream(stream);

	        if (item.isFormField()) {
	          log.warning("Got a form field: " + item.getFieldName());
	        } else {
	          log.warning("Got an uploaded file" + item.getFieldName() +
	                      ", name = " + item.getName());
	          
	          int score = 100;
	          //Now we have a file, read all the headers first
	          String name = data.readUTF();
	          String type = data.readUTF();
	          long start = data.readLong();
	          
	          // Create the object and fill in trip start time and username
	          TripData trip = new TripData(name);
	          long time = System.currentTimeMillis();
	          trip.setID(time);
	          trip.setType(type);
	          trip.setTriptime(start);
	          
	          try {
	        	  while (true) {
	        		  double val = data.readDouble();
	        		  if (val == 99999) {
	        			  break;
	        		  } else if (val == 88888) {
	        			  double lon = data.readDouble();
	        			  double lat = data.readDouble();
	        			  int abtype = data.readInt();
	        			  int severity = data.readInt();
	        			  long abtime = data.readLong();
	        			  score = score - 5 - 5 * severity;
	        			  AbPoint p = new AbPoint();
	        			  p.setLat(lat);
	        			  p.setLon(lon);
	        			  p.setSeverity(severity);
	        			  p.setType(abtype);
	        			  p.setTime(abtime);
	        			  trip.addAData(p);
	        		  } else {
	        			  Coordinate c = new Coordinate();
	        			  double lon = val;
	        			  double lat = data.readDouble();
	        			  c.setLat(lat);
	        			  c.setLon(lon);
	        			  trip.addGData(c);
	        		  }
	        	  }
	        	  long end = data.readLong();
	        	  int duration  = (int) (end - start)/1000;
	        	  trip.setDuration(duration);
	        	  trip.setScore(score);
	        	  System.out.println("score is " + score);
	          } catch (EOFException e) {
	          }
	          ofy.put(trip);
	          System.out.println("success!");
	        }
	      }
	      
	    } catch (Exception ex) {
	      throw new ServletException(ex);
	    }
	  }
}
